package org.iplugin.version;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * 　　* @Description: 版本号升级
 * 　　* @author shangyouzhi1
 * 　　* @date 2022/11/4 18:23
 */

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.iplugin.version.config.IConfigModel;
import org.iplugin.version.handler.IVersionUpdateAbstractHandler;
import org.iplugin.version.handler.IVersionUpdateModelHandler;
import org.iplugin.version.model.IModifiedPomVersion;
import java.io.File;
import java.io.FileInputStream;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.DependencyManagement;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.model.io.xpp3.MavenXpp3WriterEx;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.Execute;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.utils.WriterFactory;


@Mojo(name = "upVersion")
@Execute(goal = "upVersion", phase = LifecyclePhase.CLEAN)
public class IVersionAbstractUpdateMojo extends AbstractMojo {

    protected static final Map<String, String> newVersionMap = Maps.newHashMap();
    @Parameter(name = "versionPath")
    private String versionPath;

    @Parameter(name = "versionConfig", alias = "vconf")
    private String versionConfig;

    @Parameter(name = "versionUpdate", alias = "iVersionUpdate", defaultValue = "true")
    private boolean versionUpdate;

    @Parameter(name = "configModels", alias = "iConfigModels")
    private List<IConfigModel> configModels;
    @Parameter(defaultValue = "${plugin}", readonly = true)
    private PluginDescriptor descriptor;

    @Parameter(defaultValue = "${project}", required = true, readonly = true)
    private MavenProject project;

    @Parameter(name = "copySourceFile",alias = "copySourceFile",defaultValue = "false")
    private Boolean copySourceFile;

    @Override
    public void execute() throws MojoExecutionException {
        if (versionUpdate) {
            File file = project.getFile();
            MavenXpp3Reader reader = new MavenXpp3Reader();
            try {
                Model model = reader.read(new FileInputStream(file));
                IModifiedPomVersion modifiedPomVersion = new IModifiedPomVersion(model);
                if (CollectionUtils.isNotEmpty(configModels)) {
                    configModels.forEach(m -> newVersionMap.put(m.getGroupId() + ":" + m.getArtifactId(), m.getVersion()));
                }
                update(modifiedPomVersion);
                if (modifiedPomVersion.isModified()) {
                    writeFile(model, file);
                }
            } catch (Exception e) {
                getLog().error("读取文件异常：" + e.getMessage(), e);
            }


        }


    }

    /**
     * 更新版本号
     *
     * @param model
     */
    private void update(IModifiedPomVersion model) {
        IVersionUpdateAbstractHandler handler = new IVersionUpdateModelHandler();
        handler.updateVersion(model);
    }


    private void writeFile(Model model, File file) {
        this.getLog().info("版本发生变更，开始写pom文件");

        try {
            if(copySourceFile){
                String sourceFilePath = file.getAbsolutePath();
                long timestamp = System.currentTimeMillis();
                File copyFile = new File(sourceFilePath + ".updateVersion_" + timestamp);
                if (copyFile.exists()) {
                    copyFile.delete();
                    copyFile.createNewFile();

                }
                FileUtils.copyFile(file, copyFile);
            }
            MavenXpp3WriterEx ex = new MavenXpp3WriterEx();
            Writer xmlStreamWriter = WriterFactory.newXmlWriter(file);
            ex.write(xmlStreamWriter, model);
        } catch (Exception e) {
            this.getLog().error("pom 版本升级写文件异常");
        }

    }

    protected List<Dependency> getDependency(Model model) {
        List<Dependency> result = Lists.newArrayList();
        List<Dependency> dependencies = model.getDependencies();
        if (CollectionUtils.isNotEmpty(dependencies)) {
            result.addAll(dependencies);

        }
        DependencyManagement dependencyManagement = model.getDependencyManagement();
        if (dependencyManagement != null) {
            List<Dependency> managementDependencies = dependencyManagement.getDependencies();
            if (CollectionUtils.isNotEmpty(managementDependencies)) {
                result.addAll(managementDependencies);
            }
        }

        return result;
    }
}
